<template>
  <!-- PEPB -->
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('报告期')" prop="year">
            <div style="display: flex">
              <el-date-picker v-model="form.year" type="year" value-format="yyyy" :placeholder="$t('请选择')" style="width: 49%" @change="changeQuarter" />
              <el-select v-model="form.quarter" style="width: 49%" @change="changeQuarter">
                <el-option value="03-31" :label="$t('第一季度')" />
                <el-option value="06-30" :label="$t('第二季度')" />
                <el-option value="09-30" :label="$t('第三季度')" />
                <el-option value="12-31" :label="$t('年报')" />
              </el-select>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="choiceType === 'pe' ? ($t('年度主营业务利润') + $t('金额单位')) : ($t('总资产') + $t('金额单位'))" prop="annualMainBusinessProfit">
            <Money v-model="form.annualMainBusinessProfit" :unit="'w'" :placeholder="choiceType === 'pe' ? ($t('年度主营业务利润') + $t('金额单位')) : ($t('总资产') + $t('金额单位'))" @change="profitChanges" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="choiceType === 'pe' ? $t('对标上市公司加权平均PE倍数') : $t('对标上市公司加权平均PB倍数')" prop="averagePeMultiple">
            <span slot="label">
              <span v-if="choiceType === 'pe'">{{ $t('对标上市公司加权平均PE倍数') }}</span>
              <span v-if="choiceType === 'pb'">{{ $t('对标上市公司加权平均PB倍数') }}</span>
              <el-tooltip placement="top">
                <div slot="content">
                  <span v-if="choiceType === 'pe'">{{ $t('1. 股票信息列表中其中一条数据下, PE比例 = (主营业务利润 / 列表所有主营业务利润的和) × PE倍数') }}</span>
                  <span v-if="choiceType === 'pb'">{{ $t('1. 股票信息列表中其中一条数据下, PB比例 = (总资产 / 列表所有总资产的和) × PB倍数') }}</span>
                  <br>
                  <span v-if="choiceType === 'pe'">{{ $t('2. 对标上市公司加权平均PE倍数 = 将列表中所有计算的PE比例加和') }}</span>
                  <span v-if="choiceType === 'pb'">{{ $t('2. 对标上市公司加权平均PB倍数 = 将列表中所有计算的PB比例加和') }}</span>
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <Money v-model="form.averagePeMultiple" disabled :placeholder="choiceType === 'pe' ? $t('对标上市公司加权平均PE倍数') : $t('对标上市公司加权平均PB倍数')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('对标后公司估值') + $t('金额单位')" prop="benchmarkValuation">
            <span slot="label">
              {{ $t('对标后公司估值') }}{{ $t('金额单位') }}
              <el-tooltip placement="top">
                <div slot="content">
                  <span v-if="choiceType === 'pe'">{{ $t('年度主营业务利润 × 对标上市公司加权平均PE倍数') }}</span>
                  <span v-if="choiceType === 'pb'">{{ $t('总资产 × 对标上市公司加权平均PB倍数') }}</span>
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <Money v-model="form.benchmarkValuation" :unit="'w'" disabled :placeholder="$t('对标后公司估值')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('流动性折扣')" prop="liquidityDiscount">
            <el-input-number v-model="form.liquidityDiscount" :precision="2" :controls="false" :step="1" :min="0.01" :max="9999999" :placeholder="$t('流动性折扣')" @change="changeDiscount" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('最终公司估值') + $t('金额单位')" prop="finalCompanyValuation">
            <span slot="label">
              {{ $t('最终公司估值') }}{{ $t('金额单位') }}
              <el-tooltip placement="top">
                <div slot="content">
                  {{ $t('对标后公司估值 × 流动性折扣') }}
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <Money v-model="form.finalCompanyValuation" :unit="'w'" disabled :placeholder="$t('最终公司估值')" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('最终项目估值') + $t('金额单位')" prop="finalProjectValuation">
            <span slot="label">
              {{ $t('最终项目估值') }}{{ $t('金额单位') }}
              <el-tooltip placement="top">
                <div slot="content">
                  {{ $t('最终公司估值 × 所有投资主体对项目的持股比例和') }}
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <Money v-model="form.finalProjectValuation" :unit="'w'" disabled :placeholder="$t('最终项目估值')" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('备注')" prop="remark">
            <el-input v-model="form.remark" type="textarea" maxlength="2000" show-word-limit :placeholder="$t('备注')" />
          </el-form-item>
        </el-col>
      </el-row>
      <div>
        <div class="area-header" style="margin-top: 10px;">
          <span class="area-header-title">{{ $t('股票信息') }}</span>
        </div>
        <el-table tooltip-effect="darkTable" :data="form.stockList" border class="nowrapTable formTable">
          <el-table-column :label="$t('股票代码')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('股票代码') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'stockList.' + scope.$index + '.stockCode'" :rules="stockListRules.stockCode">
                <el-input v-model="scope.row.stockCode" :maxlength="100" :suffix-icon="showStockLoading" :placeholder="$t('股票代码')" @change="getStockInfo($event, scope.$index)" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('股票名称')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('股票名称') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'stockList.' + scope.$index + '.stockName'" :rules="stockListRules.stockName">
                <el-input v-model="scope.row.stockName" :maxlength="100" :placeholder="$t('股票名称')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('最新年报')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('最新年报') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'stockList.' + scope.$index + '.latestAnnualReport'" :rules="stockListRules.latestAnnualReport">
                <el-input v-model="scope.row.latestAnnualReport" :maxlength="100" :placeholder="$t('最新年报')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="choiceType === 'pe' ? ($t('主营业务利润') + $t('金额单位')) : ($t('总资产') + $t('金额单位'))" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ choiceType === 'pe' ? ($t('主营业务利润') + $t('金额单位')) : ($t('总资产') + $t('金额单位')) }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'stockList.' + scope.$index + '.mainBusinessProfit'" :rules="stockListRules.mainBusinessProfit">
                <money v-model="scope.row.mainBusinessProfit" :unit="'w'" :placeholder="choiceType === 'pe' ? ($t('主营业务利润') + $t('金额单位')) : ($t('总资产') + $t('金额单位'))" @change="changeProfit(scope.$index);changePE()" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('总市值') + $t('金额单位')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ $t('总市值') }} {{ $t('金额单位') }}</span>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'stockList.' + scope.$index + '.totalMarketValue'" :rules="stockListRules.totalMarketValue">
                <money v-model="scope.row.totalMarketValue" :unit="'w'" :placeholder="$t('总市值')" @change="changeProfit(scope.$index)" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="choiceType === 'pe' ? $t('PE倍数') : $t('PB倍数')" align="center">
            <template slot="header" slot-scope="{}">
              <i style="color: #ff4949;margin-right: 4px;">*</i>
              <span>{{ choiceType === 'pe' ? $t('PE倍数') : $t('PB倍数') }}</span>
              <el-tooltip>
                <div slot="content">
                  <span v-if="choiceType === 'pe'">{{ $t('总市值') + '÷' + $t('主营业务利润') }}</span>
                  <span v-if="choiceType === 'pb'">{{ $t('总市值') + '÷' + $t('总资产') }}</span>
                </div>
                <i class="el-icon-question" />
              </el-tooltip>
            </template>
            <template slot-scope="scope">
              <el-form-item :prop="'stockList.' + scope.$index + '.peMultiple'" :rules="stockListRules.peMultiple">
                <money v-model="scope.row.peMultiple" :placeholder="choiceType === 'pe' ? $t('PE倍数') : $t('PB倍数')" @change="changePE()" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('操作')" align="center" width="80">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="delStock(scope.$index, scope.row)">{{ $t('删除') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="tol">
          <el-button type="primary" icon="el-icon-plus" size="mini" @click="addStock">{{ $t('添加') }}</el-button>
          <el-button type="primary" size="mini" @click="stockCalculation">
            {{ $t('计算') }}
            <el-tooltip placement="top">
              <div slot="content">
                <span v-if="choiceType === 'pb'">{{ $t('新增或删除后,点我重新计算[对标上市公司加权平均PB倍数]') }}</span>
                <span v-if="choiceType === 'pe'">{{ $t('新增或删除后,点我重新计算[对标上市公司加权平均PE倍数]') }}</span>
              </div>
              <i class="el-icon-question" />
            </el-tooltip>
          </el-button>
        </div>
      </div>
    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <el-button @click="cancel">{{ $t('取消') }}</el-button>
      <el-button :type="'primary'" @click="submitForm">{{ $t('保存') }}</el-button>
    </div>
  </div>
</template>

<script>
import {
  getValuationMethodPepb,
  pepbByQuarterData,
  pepbStockCode
} from '@/api/deal/analysisValuation/dealAnalysisValuation.js'
import { ruoyiFloat } from '@/utils/ruoyi'
import moment from 'moment'
export default {
  components: {},
  props: {},
  data() {
    return {
      // 遮盖层
      loading: false,
      rules: {
        annualMainBusinessProfit: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        liquidityDiscount: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        year: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        quarter: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
      },
      stockListRules: {
        stockCode: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        stockName: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        latestAnnualReport: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        mainBusinessProfit: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        totalMarketValue: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }],
        peMultiple: [{ required: true, message: this.$t('必填信息'),	trigger: 'blur' }]
      },
      form: {
        annualMainBusinessProfit: undefined,
        averagePeMultiple: undefined,
        benchmarkValuation: undefined,
        liquidityDiscount: 1,
        finalCompanyValuation: undefined,
        finalProjectValuation: undefined,
        stockList: []
      },
      showStockLoading: undefined,
      choiceType: 'pe',
      parentData: {}
    }
  },
  watch: {},
  created() {
  },
  methods: {
    init(data) {
      this.choiceType = data.type
      this.parentData = data
      this.loading = true
      // 获取数据
      getValuationMethodPepb(this.parentData.dealId, this.parentData.type, this.parentData.time).then(response => {
        this.form = response.data
        // this.stockCalculation()
        this.loading = false
      })
    },
    edit(data) {
      this.choiceType = data.type
      this.form = data.data
      this.$forceUpdate()
    },
    /** 修改报告期后加载 数据 **/
    changeQuarter() {
      if (!this.isEmpty(this.form.year) && !this.isEmpty(this.form.quarter)) {
        if (this.isEmpty(this.form.stockList)) {
          this.msgWarning(this.$t('请填写股票信息'))
        } else {
          this.loading = true
          var query = JSON.parse(JSON.stringify(this.form))
          query.type = this.choiceType
          query.dealId = this.parentData.dealId
          pepbByQuarterData(query).then(response => {
            this.form = response.data
            this.stockCalculation()
            this.loading = false
          })
        }
      }
    },
    /** 股票信息列表变动重新计算 **/
    stockCalculation() {
      // 计算主表 PE倍数
      if (!this.isEmpty(this.form.stockList)) {
        var mainBusinessProfitTotal = 0
        this.form.stockList.forEach(pePbStock => {
          if (this.isEmpty(pePbStock.mainBusinessProfit)) {
            pePbStock.mainBusinessProfit = 0
          }
          if (this.isEmpty(pePbStock.totalMarketValue)) {
            pePbStock.totalMarketValue = 0
          }
          if (this.isEmpty(pePbStock.peMultiple)) {
            pePbStock.peMultiple = 0
          }
          mainBusinessProfitTotal = this.formatNum(mainBusinessProfitTotal) + this.formatNum(pePbStock.mainBusinessProfit)
        })
        var sum = 0
        this.form.stockList.forEach(stock => {
          // 计算公式: 主营业务比例 = [主营业务利润] / 所有股票的[主营业务利润]之和
          var ratio = this.formatNum(stock.mainBusinessProfit) / this.formatNum(mainBusinessProfitTotal)
          // 单个股票的PE乘积 = 主营业务比例 * 股票的PE倍数
          var peMultiple = this.formatNum(ratio) * this.formatNum(stock.peMultiple)
          // 主表PE倍数 = 所有股票的PE乘积之和
          sum += this.formatNum(peMultiple.toFixed(2))
        })
        this.form.averagePeMultiple = sum
        // 重新计算主表
        this.profitChanges(this.form.annualMainBusinessProfit)
      } else {
        this.form.averagePeMultiple = 0
      }
    },
    changeProfit(index) {
      if (!this.isEmpty(this.form.stockList[index].totalMarketValue) && !this.isEmpty(this.form.stockList[index].mainBusinessProfit)) {
        var temp = this.formatNum(this.form.stockList[index].totalMarketValue / this.form.stockList[index].mainBusinessProfit)
        if (isNaN(temp)) {
          this.form.stockList[index].peMultiple = 0
        } else {
          this.form.stockList[index].peMultiple = temp
        }
      }
    },
    /** 根据股票代码获取股票型 **/
    getStockInfo(value, index) {
      if (!this.isEmpty(value)) {
        this.showStockLoading = 'el-icon-loading'
        var time = moment().format('YYYY-MM-DD')
        if (!this.isEmpty(this.form.year) && !this.isEmpty(this.form.quarter)) {
          time = this.form.year + '-' + this.form.quarter
        }
        pepbStockCode(value, this.choiceType, time).then(response => {
          this.form.stockList[index].stockName = response.data.stockName
          // 最新年报 latestAnnualReport
          this.form.stockList[index].latestAnnualReport = response.data.latestAnnualReport
          // 主营业务利润  mainBusinessProfit
          this.form.stockList[index].mainBusinessProfit = response.data.mainBusinessProfit
          // 总市值 totalMarketValue
          this.form.stockList[index].totalMarketValue = response.data.totalMarketValue
          // 重新计算pe倍数
          this.changeProfit(index)
          this.showStockLoading = undefined
        }).catch(() => {
          this.showStockLoading = undefined
        })
      }
    },
    /** 主表PE倍数 **/
    changePE() {
      // 股票信息列表中其中一条数据下, PE比例 = (主营业务利润 / 列表所有主营业务利润的和) * PE倍数  mainBusinessProfit / sum(mainBusinessProfit) * peMultiple
      var result = 0
      var peRatio = 0
      var moneySum = 0
      this.form.stockList && this.form.stockList.forEach(item => {
        moneySum += this.formatNum(item.mainBusinessProfit)
      })
      this.form.stockList && this.form.stockList.forEach(item => {
        peRatio = this.formatNum(item.mainBusinessProfit) / moneySum
        result += peRatio * this.formatNum(item.peMultiple)
      })
      this.form.averagePeMultiple = result
    },
    /** 新增股票 **/
    addStock() {
      const row = {
        id: undefined,
        stockCode: undefined,
        stockName: undefined,
        latestAnnualReport: undefined,
        mainBusinessProfit: undefined,
        totalMarketValue: undefined,
        peMultiple: undefined
      }
      if (!(this.form.stockList instanceof Array)) {
        this.$set(this.form, 'stockList', [])
      }
      this.$nextTick(() => {
        this.form.stockList.push(row)
      })
    },
    /** 删除股票 **/
    delStock(index) {
      this.form.stockList.splice(index, 1)
    },
    /** 格式化金额, 保留精度及小数 **/
    formatNum(num) {
      if (num === null || num === undefined || isNaN(num)) {
        num = 0
      }
      return ruoyiFloat().formatNum(Number(num).toFixed(4))
    },
    /** 年度主营业务利润变化 **/
    profitChanges(val) {
      if (val) {
        // 对标后公司估值(万 =	年度主营业务利润 * 对标上市公司加权平均PE倍数 (benchmarkValuation = annualMainBusinessProfit * averagePeMultiple)
        this.form.benchmarkValuation = this.formatNum(this.form.annualMainBusinessProfit) * this.formatNum(this.form.averagePeMultiple)
        this.changeDiscount()
      } else {
        this.form.benchmarkValuation = 0
        this.form.finalCompanyValuation = 0
        this.form.finalProjectValuation = 0
      }
    },
    /** 改变折扣 **/
    changeDiscount() {
      console.log('改变折扣')
      // 最终公司估值 = 对标后公司估值 * 流动性折扣 (finalCompanyValuation = benchmarkValuation * liquidityDiscount)
      this.form.finalCompanyValuation = this.formatNum(this.form.benchmarkValuation) * this.formatNum(this.form.liquidityDiscount)
      // 最终项目估值 = 最终公司估值 * 所有投资主体对项目的持股比例和 (finalProjectValuation = finalCompanyValuation * 1)
      this.form.finalProjectValuation = this.formatNum(this.form.finalCompanyValuation) * this.formatNum(this.form.shareholdingRatio)
    },
    /** 取消 **/
    cancel() {
      this.$parent.$parent.methodPePbOpen = false
    },
    /** 提交 **/
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.$emit('pepbAddMethod', this.choiceType, this.form)
          this.cancel()
        }
      })
    }
  }
}
</script>

<style scoped>

</style>
